<template>
  <div>
    <el-card shadow="never">
      <el-form label-width="80px">
        <el-form-item label="内容">
          <el-input v-model="addForm.content" placeholder="输入发表内容" type="textarea" :rows="5" />
        </el-form-item>

        <el-form-item label="添加图片">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleImgSuccess"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" plain @click="publishBtn">发表</el-button>
          <el-button style="margin-left:16px;" @click="resetBtn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUser } from '@/utils/auth'
import { addPost } from '@/api/post'
export default {
  name: 'AddPost',
  data() {
    return {
      addForm: {
        imgList: []
      },
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
  },
  methods: {

    handleRemove(obj, fileList) {
      // 从imgList中移除
      const url = obj.response.data
      const index = this.addForm.imgList.findIndex(item => url === item)
      this.addForm.imgList.splice(index, 1)
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    handleImgSuccess(res, file) {
      this.addForm.imgList.push(res.data)
    },

    publishBtn() {
      this.addForm.userId = getUser().id
      addPost(this.addForm).then(resp => {
        this.$notifySuccess('发表成功')
      })
    },

    resetBtn() {
      this.$router.go(0)
    }

  }
}
</script>

<style lang="scss" scoped>
</style>
